package cn.weekimwee.map3d.utilk

import android.annotation.SuppressLint
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.util.Log
import android.view.View
import cn.weekimwee.map3d.R
import cn.weekimwee.map3d.overlay.DrivingRouteOverlay
import com.amap.api.maps.AMap
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.model.BitmapDescriptorFactory
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.LatLngBounds
import com.amap.api.maps.model.Marker
import com.amap.api.maps.utils.SpatialRelationUtil
import com.amap.api.maps.utils.overlay.SmoothMoveMarker
import com.amap.api.services.core.AMapException
import com.amap.api.services.core.LatLonPoint
import com.amap.api.services.route.*
import kotlinx.android.synthetic.main.activity_main4.*
import org.jetbrains.anko.toast
import java.util.ArrayList

class Main4Activity : AppCompatActivity() {
    private lateinit var aMap:AMap
    private lateinit var routeSearch:RouteSearch
    private lateinit var smoothMarker: SmoothMoveMarker
    private lateinit var drivingRouteOverlay: MyDrivingRouteOverlay
//    private lateinit var startRunThread :StartRunThread
    private val startPoint = LatLonPoint(29.86088,121.593371)
    private val endPoint = LatLonPoint(29.857785,121.580055)
    private val startLatLng = LatLng(29.86088,121.593371)
    private val latLng1 = LatLng(29.857641,121.591782)
    private val latLng2 = LatLng(29.856692,121.591439)
    private val latLng3 = LatLng(29.855454,121.591095)
    private val latLng4 = LatLng(29.853007,121.590022)
    private val latLng5 = LatLng(29.851183,121.588746)
    private val latLng6 = LatLng(29.851593,121.586117)
    private val latLng7 = LatLng(29.852151,121.582845)
    private val latLng8 = LatLng(29.852244,121.579347)
    private val latLng9 = LatLng(29.854422,121.577598)
    private val endLatLng = LatLng(29.857785,121.580055)

    private var all  = arrayListOf<LatLng>()
    private var now = arrayListOf<LatLng>()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main4)
        mapView.onCreate(savedInstanceState)
        toast("lalalllalalalla")
        aMap = mapView.map
        routeSearch = RouteSearch(this)
        routeSearch.setRouteSearchListener(object: RouteSearch.OnRouteSearchListener{
            override fun onDriveRouteSearched(p0: DriveRouteResult?, p1: Int) {
                if(p1 == AMapException.CODE_AMAP_SUCCESS){
                    p0?.let {
                        p0.paths?.let {
                            for (path in p0.paths) {
                                Log.e("eeeee", "path-->" + path.steps)
                                for(step in path.steps){
                                    Log.e("eeeee","step-->"+step.road)
                                    for(latLon in step.polyline){
                                        Log.e("eeeee","lat:${latLon.latitude}-->lon:${latLon.longitude}")
                                    }
                                }
                            }
                            val drivePath = p0.paths[0]
//                            drivingRouteOverlay = MyDrivingRouteOverlay(this@Main4Activity, aMap, drivePath, p0.startPos, p0.targetPos, null)
//                            drivingRouteOverlay.setNodeIconVisibility(false)
//                            drivingRouteOverlay.setIsColorfulline(false)
//                            drivingRouteOverlay.removeFromMap()
//                            drivingRouteOverlay.addToMap()
//                            drivingRouteOverlay.zoomToSpan()
                        }
                    }
                }else{
                    toast("没搜索到数据...")
                }
            }

            override fun onBusRouteSearched(p0: BusRouteResult?, p1: Int) {
            }

            override fun onRideRouteSearched(p0: RideRouteResult?, p1: Int) {
            }

            override fun onWalkRouteSearched(p0: WalkRouteResult?, p1: Int) {
            }

        })
        var fromAndTo = RouteSearch.FromAndTo(startPoint, endPoint)
        var query = RouteSearch.DriveRouteQuery(fromAndTo, RouteSearch.DrivingDefault, null,
                null, "")// 第一个参数表示路径规划的起点和终点，第二个参数表示驾车模式，第三个参数表示途经点，第四个参数表示避让区域，第五个参数表示避让道路
        routeSearch.calculateDriveRouteAsyn(query)// 异步路径规划驾车模式查询
        /*all.add(startLatLng)
        all.add(latLng1)
        all.add(latLng2)
        all.add(latLng3)
        all.add(latLng4)
        all.add(latLng5)
        all.add(latLng6)
        all.add(latLng7)
        all.add(latLng8)
        all.add(latLng9)
        all.add(endLatLng)*/

        /*
        smoothMarker = SmoothMoveMarker(aMap)
        startRunThread = StartRunThread()
        startRunThread.start()*/
    }

    /**
     * 方法必须重写
     */
    override fun onResume() {
        super.onResume()
        mapView.onResume()
    }

    /**
     * 方法必须重写
     */
    override fun onPause() {
        super.onPause()
        mapView.onPause()
    }

    /**
     * 方法必须重写
     */
    override fun onSaveInstanceState(outState: Bundle?) {
        super.onSaveInstanceState(outState)
        mapView.onSaveInstanceState(outState)
    }

    /**
     * 方法必须重写
     */
    override fun onDestroy() {
        super.onDestroy()
        mapView.onDestroy()
    }

    fun startMove(){
        var bounds = LatLngBounds(now[0], now[1])
        aMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 50))

        smoothMarker.setDescriptor(BitmapDescriptorFactory.fromResource(R.drawable.icon_car))

        // 取轨迹点的第一个点 作为 平滑移动的启动
        val drivePoint = now[0]
        val pair = SpatialRelationUtil.calShortestDistancePoint(now, drivePoint)
        now[pair.first] = drivePoint
        val subList = now.subList(pair.first, now.size)

        // 设置轨迹点
        smoothMarker.setPoints(subList)
        // 设置平滑移动的总时间  单位  秒
        smoothMarker.setTotalDuration(4)

        // 设置  自定义的InfoWindow 适配器
        aMap.setInfoWindowAdapter(object : AMap.InfoWindowAdapter {
            override fun getInfoWindow(marker: Marker): View? {
                return null
            }

            override fun getInfoContents(marker: Marker): View? {
                return null
            }
        })
        // 显示 infowindow
        smoothMarker.marker.showInfoWindow()
        smoothMarker.startSmoothMove()
    }

    /*private val handler = @SuppressLint("HandlerLeak")
    object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            Log.e("eeeee", "message---->")
            if (now == null || now.size == 0) {
                now = ArrayList()
                now.add(all.removeAt(0))
            } else if (now.size == 1) {
                if (all.size != 0)
                    now.add(all.removeAt(0))
                else
                    startRunThread.close()
            } else if (now.size == 2) {
                //开始跑
                drivingRouteOverlay.removeStartMarker()
                if (smoothMarker != null) smoothMarker.destroy()
                startMove()
                now.removeAt(0)
            } else if (now.size != 0 && all.size == 0) {
                startRunThread.close()
            }
        }
    }*/


   /* internal inner class StartRunThread : Thread() {
        var isRun = true
        override fun run() {
            super.run()
            try {
                while (isRun) {
                    handler.sendEmptyMessage(0)
                    Thread.sleep(3000)
                }
            } catch (e: InterruptedException) {
                e.printStackTrace()
            }

        }

        fun close() {
            isRun = false
        }
    }*/
}
